package main

import (
	"flag"
	"io"
	"strings"

	"github.com/azhai/gozzo-net/network"
	"github.com/azhai/gozzo-net/unix"
	"github.com/azhai/gozzo-utils/logging"

	"red-agate/resp"
)

var (
	port    uint
	verbose bool
	logger  *logging.Logger
	spliter *resp.SplitMatcher
)

// 解析参数
func init() {
	// 端口，三选一
	flag.UintVar(&port, "p", 6380, "server的端口")
	flag.BoolVar(&verbose, "v", false, "输出详细信息")
	flag.Parse()

	logger = logging.NewLogger("DEBUG", "./logs")
	spliter = resp.NewSpliterResp2()
}

// 创建应用
func main() {
	// 目标（真实）服务器
	addr := network.NewTCPAddr("10.10.20.80", 6379)
	relayer := unix.NewRelayer(addr)
	// 代理转发
	events := network.Events{}
	proxy := unix.NewProxy("tcp", "", uint16(port))
	events.Process = proxy.CreateProcess(relayer, RelayData)
	proxy.Run(events)
}

// RelayData 原样复制输入和输出
func RelayData(s *network.Server, orig, relay *network.Conn) {
	defer relay.Close()
	go io.Copy(orig.GetRawConn(), relay.GetReader()) // 复制服务端回应
	addr := orig.GetRawConn().RemoteAddr().String()
	err := spliter.Scanning(orig.GetReader(), func(data []byte) {
		relay.QuickSend(ProcessData(addr, data))
	})
	if err != nil && logger != nil {
		logger.Error(err)
	}
}

// ProcessData 处理数据
func ProcessData(addr string, data []byte) []byte {
	if logger != nil {
		logger.Debug(addr, "\t", resp.QuoteBytes(data))
	}
	word := strings.ToLower(string(data))
	if strings.HasPrefix(word, "*2\r\n$8\r\nrel.good\r\n") {
		tail := word[len("*2\r\n$8\r\nrel.good\r\n")+4:]
		data = []byte("*2\r\n$7\r\nhgetall\r\n$21\r\nrelation-good:" + tail)
		logger.Info(addr, "\t", resp.QuoteBytes(data))
	}
	return data
}
